package com.oceanstar.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {

    // 使用 b2NlYW5zdGFy 作为密钥
    private static final String SECRET_KEY = "b2NlYW5zdGFyb2NlYW5zdGFyb2NlYW5zdGFyb2NlYW5zdGFyb2NlYW5zdGFyb2NlYW5zdGFy";
    private static final long EXPIRATION_TIME = 365L* 24 * 60 * 60 * 1000; // 10天

    // 生成JWT令牌
    public static String generateToken(Map<String, Object> claims) {
        Date now = new Date();
        Date expiration = new Date(now.getTime() + EXPIRATION_TIME);

        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .addClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis()+ EXPIRATION_TIME))
                .compact();
    }



    // 解析JWT令牌
    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();
    }


    public static void main(String[] args) {
        // 测试生成和解析JWT令牌
        try {
            // 创建自定义声明
            Map<String, Object> claims = new HashMap<>();
            claims.put("sub", "user123"); // 设置主题
            claims.put("role", "admin"); // 自定义声明

            // 生成JWT令牌
            String token = generateToken(claims);
            System.out.println("Generated Token: " + token);

            // 解析JWT令牌
            Claims parsedClaims = parseToken(token);
            System.out.println("Subject: " + parsedClaims.getSubject());
            System.out.println("Expiration: " + parsedClaims.getExpiration());
            System.out.println("Custom Role: " + parsedClaims.get("role"));
        } catch (Exception e) {
            System.err.println("JWT test failed: " + e.getMessage());
        }
    }



}